<?php
/*
 * 微信模板信息推送
 */
namespace Think\Wxpay;

use Common\Model\MailModModel;
use Common\Model\MemberOtherPlatformModel;
use Common\Model\WeixinTokenModel;
use Think\Curl;
use Think\Helper;
use Think\Wxpay\Wxpay;
class Wxpush
{
    /**
     * 帐号配置
     * @var
     */
    private $accountsConf = [
        //洋玩易  正式账号  洋玩易平台
        'gh_bfc025005d01' => [   //gh_bfc025005d01 新洋玩意  gh_1cebae3dcfc7  点点拿
            'appid' => 'wxac2a54fc8d293824',   //新洋玩易  wxac2a54fc8d293824  点点拿 wx88c66a1811791b74
            'appsecret' => 'c3e737dbfa93c2fa3a0beb3523680d87',   //新洋玩易  c3e737dbfa93c2fa3a0beb3523680d87  点点拿    f3b963ab6edb23ffa22ceaf1b17164e2
            'msgtpl' => [
                // 开店成功通知
                'openShopSuccess' => [
                    'id' => '-7fPGxXBY3soOJnYdPNrASErYi0gIZnY4xlgAZ2y7MA',
                    'params' => ['first','keyword1','keyword2','remark']
                ],
                // 订单已发货通知
                'orderShipped' => [
                    'id' => '9IjX3krjCVCPECLhVjqlyY_FkOaDmOBo3RV0v0ht6m0',
                    'params' => ['first','keyword1','keyword2','keyword3','keyword4','remark']
                ],
                // 店铺新订单成交通知
                'shopOrderSuccess' => [
                    'id' => 'TS8A6UkrhCNTboXx4Qg6Q5klz3_YGWvoryHq6rC7o1k',
                    'params' => ['first','keyword1','keyword2','keyword3','keyword4','remark']
                ],
                // 提现提交通知
                'withdrawSubmit' => [
                    'id' => 'Lu_h4w7m5U7x3D5QAJLRd6beX7yIP-T2oGkIUiciHn4',
                    'params' => ['first','money','timet','remark']
                ],
                // 提现失败通知
                'withdrawFaild' => [
                    'id' => 'TkoKvByLv-ySvd4-07mkdmWkwEZire-iNFPSvfymz0E',
                    'params' => ['first','money','time','remark']
                ],
                // 提现成功通知
                'withdrawSuccess' => [
                    'id' => 'yf2neZWEoA-UO5TOzD_39YcMZs5EjLGQqZfBdSh9d1A',
                    'params' => ['first','money','timet','remark']
                ],
                // 福利到帐提醒
                'bonusRemind' => [
                    'id' => '9Teog1ZSRPOAdd7dRg3GTYioWXO23_8W463h06Zz6SE',
                    'params' => ['first','keyword1','keyword2','remark']
                ],

                //上级订单收益提醒
                'parentOrderSuccess' => [
                    'id' => 'wedB8Ict7TdyHQqztx9jjENLRs8oiEWjK6oDcw4EN1w',
                    'params' => ['first','keyword1','keyword2','remark']
                ],
                // 付款成功通知
                'orderPaySuccess' => [
                    'id' => '2_EGomdMdywC3Jhp9ycY_wRAJk0BOVhGUxJCaOOf3OM',
                    'params' => ['first','orderProductPrice','orderProductName','orderAddress','orderName','remark']
                ],
                //给上级店铺推送订单消息
                'shopOrderSuceess' => [
                    'id' => '-8JMyQ1BdFjXB8WZ8FofAQYerpwAsRUWOX-XA_f5L30',
                    'params' => ['first','keyword1','keyword2','keyword3','remark']
                ],
                // 店铺升级成功通知--成为合伙人
                'shopUpgradeSuccess' => [
                    'id' => 'PaBFoZL2_8hOst7cA2kb-iF_ZSfXsx_y-aIJ075Rung',
                    'params' => ['first','keyword1','keyword2','remark']
                ],
                //拼团成功通知
                'pinTuanSuccess' => [
                    'id' => 'V9vWQ2uIXXYW34DDcKB5PcL6fIMbJycbYIEAZkNS9go',
                    'params' => ['first','keyword1','keyword2','keyword3','remark']
                ],
                //推荐奖励通知
                'tuijianSuccess' => [
                    'id' => 'HRL2pyZnIRcIf31wmhEbRz4zjgNUm_0FAAmDHBw1CS8',
                    'params' => ['first','keyword1','keyword2','keyword3','remark']
                ],
                //膜法伊人订单成功通知
                'magicSuccess' => [
                    'id' => 'iYnLv5PCeqCuljJOFv0VLiCZ21KrMsEE8Uzzfplb0g0',
                    'params' => ['first','keyword1','keyword2','keyword3','keyword4','remark']
                ],
                //新用户入驻通知
                'newUserInfoSuceess' => [
                    'id' => 'tghBgko5E5d0wub2zqm5IvqB0J1-yxv4d_NOGRt7cg4',
                    'params' => ['first','keyword1','keyword2','remark']
                ]

            ]
        ],
        //洋玩易 测试帐号    点点拿平台
        'gh_1cebae3dcfc7' => [      //gh_bfc025005d01 新洋玩意  gh_1cebae3dcfc7  点点拿
            'appid' => 'wx88c66a1811791b74',    //新洋玩易  wxac2a54fc8d293824  点点拿 wx88c66a1811791b74
            'appsecret' => 'f3b963ab6edb23ffa22ceaf1b17164e2',  //新洋玩易  eb7190cb7635c41f472eba23a790c180  点点拿    f3b963ab6edb23ffa22ceaf1b17164e2
            'msgtpl' => [
                // 开店成功通知
                'openShopSuccess' => [
                    'id' => 'cO5zMK-EbcjUqE-mTIs4cTEiAMQYGYoPtxkAVi6nkF8',
                    'params' => ['first','keyword1','keyword2','remark']
                ],
                // 订单已发货通知
                'orderShipped' => [
                    'id' => 'oKB6nvxSYJCPojlGxFehiQGXYn7A-KBfENkXUvIz9jU',
                    'params' => ['first','keyword1','keyword2','keyword3','keyword4','remark']
                ],
                // 店铺新订单成交通知
                'shopOrderSuccess' => [
                    'id' => 'ona7U3wJPHnb2sg9x6UcaQADL6wuKWnpBSAmM6OZFp8',
                    'params' => ['first','keyword1','keyword2','keyword3','keyword4','remark']
                ],
                // 提现提交通知
                'withdrawSubmit' => [
                    'id' => 'pnR5YhdzlHbrH8uDm6acjK41L-sGDASPc1paCmKWP_s',
                    'params' => ['first','money','timet','remark']
                ],
                // 提现失败通知
                'withdrawFaild' => [
                    'id' => 'QJVYtVZ61C-V4RM9gOaQtMSD8w_rK48K3mPxnVdlK10',
                    'params' => ['first','money','time','remark']
                ],
                // 提现成功通知
                'withdrawSuccess' => [
                    'id' => 'dau-5v5dBUhKA8-YGSSgrpsvxPsZiXs2cNiFB1mFdnU',
                    'params' => ['first','money','timet','remark']
                ],
                // 红包领取提醒
                //                 'bonusRemind' => [
                //                     'id' => 'i1I67bW8w-_Z4jAt5wm53I-lfOaE7LOIKUjqhUor_dE',
                //                     'params' => ['first','keyword1','keyword2','remark']
                //                 ],
                //                 // 付款成功通知
                'orderPaySuccess' => [
                    'id' => '2_EGomdMdywC3Jhp9ycY_wRAJk0BOVhGUxJCaOOf3OM',
                    'params' => ['first','orderProductPrice','orderProductName','orderAddress','orderName','remark']
                ],
                // 店铺升级成功通知
                'shopUpgradeSuccess' => [
                    'id' => 'PaBFoZL2_8hOst7cA2kb-iF_ZSfXsx_y-aIJ075Rung',
                    'params' => ['first','keyword1','keyword2','remark']
                ],
                //拼团成功通知
                'pinTuanSuccess' => [
                    'id' => 'wcKHdJERrLz94sm07lWPHJUI36FJ5F3MX7RXCm5F2hQ',
                    'params' => ['first','keyword1','keyword2','keyword3','remark']
                ],
                //推荐奖励通知
                'tuijianSuccess' => [
                    'id' => 'HRL2pyZnIRcIf31wmhEbRz4zjgNUm_0FAAmDHBw1CS8',
                    'params' => ['first','keyword1','keyword2','keyword3','remark']
                ],
                'magicSuccess' => [
                    'id' => 'iYnLv5PCeqCuljJOFv0VLiCZ21KrMsEE8Uzzfplb0g0',
                    'params' => ['first','keyword1','keyword2','keyword3','keyword4','remark']
                ]
            ]
        ],
        'ywy_oline' => [   //gh_bfc025005d01 新洋玩意  gh_1cebae3dcfc7  点点拿
            'appid' => 'wxac2a54fc8d293824',   //新洋玩易  wxac2a54fc8d293824  点点拿 wx88c66a1811791b74
            'appsecret' => 'c3e737dbfa93c2fa3a0beb3523680d87'   //新洋玩易  c3e737dbfa93c2fa3a0beb3523680d87  点点拿    f3b963ab6edb23ffa22ceaf1b17164e2
        ]
    ];
    // 消息推送接口
    private $wxTplApi = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s';

    /**
     * 获取微信号的access_token
     * @param string $weixin
     */
    public function getAccessToken($weixin)
    {
        $model = new WeixinTokenModel();
        $info = $model->getOne('access_token', $weixin);
        if (is_null($info) || strtotime($info->create_time) < (time() - 6000)) {
            //如果没有或记录超过了60分钟，则重新获取
             $accessToken = $this->refreshAccessToken($weixin);
            if ($accessToken == '') {
                return ['code'=>300,'msg'=>'access_token更新失败'];
            }
        } else {
            $accessToken = $info['value'];
        }
        return $accessToken;
    }

    /**
     * 刷新access_token
     * @param string $weixin 微信帐号
     * @return string 返回 access token
     */
    protected function refreshAccessToken($weixin)
    {

        if (!isset($this->accountsConf[$weixin])) {
            return ['code'=>300,'msg'=>'微信账号不存在'];
        }
        $accontInfo = $this->accountsConf[$weixin];

        //获取token
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
        $url = sprintf($url, $accontInfo['appid'], $accontInfo['appsecret']);

        $curl = new Curl();
        $curl->get($url);
        $resArr = json_decode($curl->rawResponse, true);

        //写入数据库
        $model = new WeixinTokenModel();
        $data['account']    = $weixin;
        $data['name']       = 'access_token';
        $data['value']      = $resArr['access_token'];
        $data['create_time']   = date('Y-m-d H:i:s',time());
        $model->add($data);

        return $resArr['access_token'];
    }

    /**
     * 支付成功消息推送
     * @param integer $memberId
     * @param string $type
     * @param string $json
     */
    public function msgPush($memberId, $type, $json){
        $weixin = 'gh_bfc025005d01';
//         $token = $this->getAccessToken($weixin);
        $wxtpl = $this->getWxMsgTpl($weixin, $type);

        $appid = $this->accountsConf[$weixin]['appid'];
        $secret = $this->accountsConf[$weixin]['appsecret'];
        $token = $this->getAccessTokens($appid,$secret);
        $api = sprintf($this->wxTplApi, $token);

        $tplId = $wxtpl['id'];
        $tplData = $this->getTplParam($wxtpl['params'], json_encode($json));
        $jsonArr = json_decode($json);
        $url = $json['url'];
        $model = new MemberOtherPlatformModel();
        $openId = $model->getWeixinOpenIdByMemberId($memberId);

        $flg = $openId;
        $data = [
            "touser" => $flg,
            "template_id" => $tplId,
            "url" => $url,
            "data" => $tplData
        ];
        $Helper = new Helper();
        $res = $Helper::curl_file_get_contents($api, json_encode($data));
        $res = json_decode($res, true);
        return $res;
    }
    public function getAccessTokens($appid,$secret){


        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
        $tempArr = json_decode($this->httpGet($url));
        if (@array_key_exists ( 'access_token', $tempArr )) {
            $access_token = $tempArr->access_token;
            return $access_token;
        } else {
            return 0;
        }
    }
    public function httpGet($url) {
        $curl = curl_init();
        //$url = 'https://www.baidu.com';
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        //curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/8.0.3 Safari/600.3.18");
        $res = curl_exec($curl);
        //var_dump($res);die();
        curl_close($curl);

        return $res;
    }

    /**
     * 获取消息模板参数
     * @param array $params
     * @param string $json
     */
    protected function getTplParam($params, $json){
        $data = json_decode($json, true);
        $return  = [];
        foreach ($params as $param){
            isset($data[$param]) && $return[$param] = ['value'=>$data[$param]];
        }
        return $return;
    }
    /**
     * 获取微信推送模板
     * @param string $weixin
     * @param string $type
     */
    protected function getWxMsgTpl($weixin, $type){
        $tpl = $this->accountsConf[$weixin]['msgtpl'][$type];
        return $tpl;
    }

    /**
     * 获取某推送信息内容
     * @param unknown $flag 模板标识
     * @param unknown $replaceArr 需要替换字符对应的数组
     */
    public function getMessageDetail($flag,$replaceArr)
    {
        $model = new MailModModel();
        $message = $model->getOne($flag);
        if(!empty($message)){
            //开始替换
            if(!empty($replaceArr)){
                foreach ($replaceArr as $k=>$v)
                {
                    $need_replace = [];
                    if(isset($message[$k])){
                        preg_match_all('/(\{\{(\w+)\}\})/', $message[$k],$need_replace);
                        foreach ($need_replace[0] as $vv)
                        {
                            $replaceStr = '';
                            if(isset($v[$vv])){
                                $replaceStr = $v[$vv];
                            }
                            $message[$k] = str_replace($vv, $replaceStr, $message[$k]);
                        }
                    }
                }
            }
        }

        return $message;
    }
}